from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from pydantic import BaseModel
from typing import Optional
from starlette.status import HTTP_401_UNAUTHORIZED
router = APIRouter()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl='/token')


class User(BaseModel):
    username: str
    email: Optional[str] = None
    full_name: Optional[str] = None
    disable: Optional[str] = None


fake_users_db = {
    'lly': {
        'username': 'lly',
        'full_name': 'liluyue',
        'disable': False,
    }
}


def get_current_active_user(token: str = Depends(oauth2_scheme)):
    if token in fake_users_db:
        user_dict = fake_users_db[token]
        if user_dict:
            return User(**user_dict)
    raise HTTPException(
        status_code=HTTP_401_UNAUTHORIZED,
        detail="Invalid authentication credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )


@router.post('/token')
def login(form_data: OAuth2PasswordRequestForm = Depends()):
    user_dict = form_data.username
    if form_data.username not in fake_users_db:
        raise HTTPException(status_code=400,
                            detail='Incorrect username or password',
                            )
    return {'access_token': form_data.username, 'token_type': 'bearer'}


@router.get('/users/me')
def read_users_me(current_user: User = Depends(get_current_active_user)):
    return current_user
